﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web.Helpers;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using ReportFramework.Common;
using ReportFramework.EntityFramework;
using ReportFramework.Models;
using System.IO;

namespace ReportFramework.Controllers
{
    public class HomeController : Controller
    {
        private string _rptName = "";
        public bool InitialConfig()
        {
            try
            {
                var fileOrDirectoryPath = Server.MapPath(@"~/ReportFramework/templates/" + _rptName);
                var reportTemplatesCommentsList = new List<ReportTemplatesCommentsModel>();
                int serialNum = 1;
                if (System.IO.Directory.Exists(fileOrDirectoryPath))
                {
                    IOHelper.ReadReportTemplatesCommentsToList(new DirectoryInfo(fileOrDirectoryPath),
                        ref reportTemplatesCommentsList, ref serialNum, null);
                    TempData["Config"] = new { client = reportTemplatesCommentsList };
                    TempData["Menu"] = new { menu = reportTemplatesCommentsList };
                }
                else if (System.IO.File.Exists(fileOrDirectoryPath))
                {
                    //parse file
                    var fileContents = System.IO.File.ReadAllText(fileOrDirectoryPath);
                    dynamic config = Newtonsoft.Json.JsonConvert.DeserializeObject(fileContents);
                    TempData["Config"] = config;
                    TempData["DefaultModelNameSpace"] = config.server.defaultModelNameSpace;
                    TempData["DefaultPageSize"] = config.server.defaultPageSize;

                    //Get current menus
                    IOHelper.ReadReportTemplatesCommentsToList(new DirectoryInfo(fileOrDirectoryPath.Substring(0, fileOrDirectoryPath.LastIndexOf('\\') + 1)),
                              ref reportTemplatesCommentsList, ref serialNum, null);
                    TempData["Menu"] = new { menu = reportTemplatesCommentsList };
                }
                else
                {
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public dynamic GetConfigClient()
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(new { client = (TempData.Peek("Config") as dynamic).client, menu = (TempData.Peek("Menu") as dynamic).menu });
            }
            catch (Exception)
            {
                return "";
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Report(string id)
        {
            _rptName = id;
            if (InitialConfig())
            {
                return View();
            }
            else
            {
                return Redirect("/Error/Index");
            }
        }

        /// <summary>
        /// 只支持但条件like查询，仅用于先拉菜单或自动填充菜单用
        /// </summary>
        /// <param name="spFuncName"></param>
        /// <param name="filterStr"></param>
        /// <param name="filterToFields"></param>
        /// <param name="pageSize"></param>
        /// <param name="skip"></param>
        /// <returns></returns>
        public ActionResult GetTbDataWithContainsFilter(string spFuncName, string filterStr, string filterToFields, int pageSize = 0, int skip = 0)
        {
            pageSize = pageSize != 0 ? pageSize: ConvertHelper.ConvertInt(TempData.Peek("DefaultPageSize"));
            var filterToFieldDic = ConvertHelper.ConvertfilterFieldsToDic(filterToFields);
            var sql = string.Format(@"select * from {0}", spFuncName);
            var sqlParameter = new List<SqlParameter>();
            dynamic filter = Newtonsoft.Json.JsonConvert.DeserializeObject(filterStr);
            if (filter.title != null && filter.value.Value!="")
            {
                var fieldName = filter.title.Value;
                var fieldValue = filter.value.Value;
                if (!(filterToFieldDic.Count > 0 && !filterToFieldDic.ContainsKey(fieldName)))
                {
                    if (filterToFieldDic.ContainsKey(fieldName))
                    {
                        fieldName = filterToFieldDic[fieldName];
                    }
                    sql += string.Format(" where {0} LIKE N'%'+{1}+'%'", fieldName, "@" + fieldName);
                    sqlParameter.Add(new SqlParameter("@" + fieldName, fieldValue));
                }
            }
            using (var entities = new RMSEntities())
            {
                var retVal = sqlParameter.Count > 0
                    ? ReflectionHelper.CSqlQuery(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql, pageSize, skip,
                        sqlParameter.ToArray())
                    : ReflectionHelper.CSqlQuery(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql, pageSize, skip);
                return Json(retVal["data"]);
            }
        }

        /// <summary>
        /// 支持多条件 in 过滤
        /// </summary>
        /// <param name="spFuncName"></param>
        /// <param name="filterStr"></param>
        /// <param name="filterToFields"></param>
        /// <param name="pageSize"></param>
        /// <param name="skip"></param>
        /// <returns></returns>
        public ActionResult GetTbDataWithInFilters(string spFuncName, string filterStr, string filterToFields, int pageSize = 0, int skip = 0)
        {
            pageSize = pageSize != 0 ? pageSize : ConvertHelper.ConvertInt(TempData.Peek("DefaultPageSize"));
            var filterToFieldDic = ConvertHelper.ConvertfilterFieldsToDic(filterToFields);
            var sql = string.Format(@"select * from {0}", spFuncName);
            var sqlParameters = new List<SqlParameter>();
            dynamic filter = Newtonsoft.Json.JsonConvert.DeserializeObject(filterStr);
            foreach (var item in filter)
            {
                var fieldName = item.title.Value;
                var fieldValue = item.value.Value;
                if (filterToFieldDic.Count > 0)
                {
                    if (filterToFieldDic.ContainsKey(fieldName))
                    {
                        fieldName = filterToFieldDic[fieldName];
                    }
                    else
                    {
                        continue;
                    }
                }

                //ValidateQuery 防sql注入
                if (fieldValue == "" || ConvertHelper.ValidateQuery(fieldValue)) continue;
                sql += string.Format(" where {0} in ('{1}')", fieldName,
                    fieldValue.Replace(",", "','"));
                //sqlParameters.Add(new SqlParameter("@" + item.title.Value, values));
            }
            if (!sql.Contains("where"))
            {
                sql += " where 1=2";
            }
            using (var entities = new RMSEntities())
            {
                var retVal = sqlParameters.Count > 0
                    ? ReflectionHelper.CSqlQuery(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql, pageSize, skip,
                        sqlParameters.ToArray())
                    : ReflectionHelper.CSqlQuery(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql, pageSize, skip);
                if (retVal == null)
                {
                    return Json(new Dictionary<string, object> { { "total", 0 }, { "data", "{}" } });
                }
                return Json(retVal);
            }
        }

        public ActionResult GetFuncData(string spFuncName, string filterStr, string filterToFields, int pageSize = 0, int skip = 0)
        {
            pageSize = pageSize != 0 ? pageSize : ConvertHelper.ConvertInt(TempData.Peek("DefaultPageSize"));
            var dics = new Dictionary<string, string>(); //for procedure params
            var filterToFieldDic = ConvertHelper.ConvertfilterFieldsToDic(filterToFields);
            dynamic filter = Newtonsoft.Json.JsonConvert.DeserializeObject(filterStr);
            foreach (var item in filter)
            {
                var fieldName = item.title.Value;
                var fieldValue = item.value.Value;
                if (fieldValue != "")
                {

                    if (filterToFieldDic.Count > 0)
                    {
                        if (filterToFieldDic.ContainsKey(fieldName))
                        {
                            fieldName = filterToFieldDic[fieldName];
                        }
                        else
                        {
                            continue;
                        }
                    }

                    dics.Add(fieldName, fieldValue);
                }
            }
            using (var entities = new RMSEntities())
            {
                var retVal = ReflectionHelper.GetFuncValue(entities, spFuncName,
                    TempData.Peek("DefaultModelNameSpace") + "." + spFuncName + "_Result", pageSize, skip, dics);
                if (retVal == null)
                {
                    return Json(new Dictionary<string, object> {{"total", 0}, {"data", "{}"}});
                }
                return Json(retVal);
            }
        }

        public ActionResult GetFuncDataAll(string spFuncName, string filterStr, string filterToFields)
        {
            var dics = new Dictionary<string, string>(); //for procedure params
            var filterToFieldDic = ConvertHelper.ConvertfilterFieldsToDic(filterToFields);
            dynamic filter = Newtonsoft.Json.JsonConvert.DeserializeObject(filterStr);
            foreach (var item in filter)
            {
                var fieldName = item.title.Value;
                var fieldValue = item.value.Value;
                if (fieldValue != "")
                {

                    if (filterToFieldDic.Count > 0)
                    {
                        if (filterToFieldDic.ContainsKey(fieldName))
                        {
                            fieldName = filterToFieldDic[fieldName];
                        }
                        else
                        {
                            continue;
                        }
                    }

                    dics.Add(fieldName, fieldValue);
                }
            }
            using (var entities = new RMSEntities())
            {
                var retVal = ReflectionHelper.GetFuncValueAll(entities, spFuncName,
                    TempData.Peek("DefaultModelNameSpace") + "." + spFuncName + "_Result", dics);
                if (retVal == null)
                {
                    return Json(new Dictionary<string, object> { { "data", "{}" } });
                }
                return new JsonResult { Data = retVal, MaxJsonLength = 86753090 };
            }
        }

        /// <summary>
        /// 支持多条件 in 过滤
        /// </summary>
        /// <param name="spFuncName"></param>
        /// <param name="filterStr"></param>
        /// <param name="filterToFields"></param>
        /// <param name="pageSize"></param>
        /// <param name="skip"></param>
        /// <returns></returns>
        public ActionResult GetTbDataWithInFiltersAll(string spFuncName, string filterStr, string filterToFields)
        {
            var filterToFieldDic = ConvertHelper.ConvertfilterFieldsToDic(filterToFields);
            var sql = string.Format(@"select * from {0}", spFuncName);
            var sqlParameters = new List<SqlParameter>();
            dynamic filter = Newtonsoft.Json.JsonConvert.DeserializeObject(filterStr);
            foreach (var item in filter)
            {
                var fieldName = item.title.Value;
                var fieldValue = item.value.Value;
                if (filterToFieldDic.Count > 0)
                {
                    if (filterToFieldDic.ContainsKey(fieldName))
                    {
                        fieldName = filterToFieldDic[fieldName];
                    }
                    else
                    {
                        continue;
                    }
                }

                //ValidateQuery 防sql注入
                if (fieldValue == "" || ConvertHelper.ValidateQuery(fieldValue)) continue;
                sql += string.Format(" where {0} in ('{1}')", fieldName,
                    fieldValue.Replace(",", "','"));
                //sqlParameters.Add(new SqlParameter("@" + item.title.Value, values));
            }
            if (!sql.Contains("where"))
            {
                sql += " where 1=2";
            }
            using (var entities = new RMSEntities())
            {
                var retVal = sqlParameters.Count > 0
                    ? ReflectionHelper.CSqlQueryAll(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql, 
                        sqlParameters.ToArray())
                    : ReflectionHelper.CSqlQueryAll(entities, TempData.Peek("DefaultModelNameSpace") + "." + spFuncName, sql);
                if (retVal == null)
                {
                    return Json(new Dictionary<string, object> { { "total", 0 }, { "data", "{}" } });
                }
                return new JsonResult {Data = retVal, MaxJsonLength = 86753090};
            }
        }
    }
}